/********************************************
 * 
 * 타이틀 : 데이터 송수신용 클래스
 * 기능 : 
 * 작성자 : LJI
 * 작성일 : 2013.09.26
 * 
 ********************************************/


package com.game.pacman.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

//데이터 송수신 기능만 구현
public class NetUnit extends Thread{
	private Client client;
	
	private Socket socket;
	private BufferedReader breader;
	private PrintStream pstream;
	private boolean running;
	
	public NetUnit(Client client, Socket socket) throws IOException {
		this.client=client;
		this.socket=socket;
		breader=new BufferedReader(
				new InputStreamReader(socket.getInputStream()));
		pstream = new PrintStream(socket.getOutputStream());
	}
	
	@Override
	public void run(){
		running=true;
		while(running){
			//메시지 수신 처리
			try {
				InputStream istream = socket.getInputStream();
				//available() : 수신된 메시지의 데이터 양을 반환
				//->if(socket.getInputStream().available()>0)과 같이 한주롤 표현가능함.
				if(istream.available()>0){
					String line = breader.readLine();
					//수신된 메시지 처리
					client.processMessage(line);
				} else {
					Thread.sleep(10);
				}
			} catch (Exception ex) {
				running = false;
				doClose();
				ex.printStackTrace();
			}
		}
	}
	
	public void doSend(String message){
		pstream.println(message);
		pstream.flush();
	}
	
	public void doStop(){
		running=false;
		doClose();	
	}

	private void doClose() {
		try{breader.close(); } catch(Exception ex){}
		try{pstream.close(); } catch(Exception ex){}
		try{socket.close(); } catch(Exception ex){}
	}
}
